<template>
  <su-fixed
    :noFixed="props.noFixed"
    :alway="props.alway"
    :bgStyles="props.bgStyles"
    :val="0"
    :index="props.zIndex"
    noNav
    :bg="props.bg"
    :ui="props.ui"
    :opacity="props.opacity"
    :placeholder="props.placeholder"
    :backgroundColor="backgroundColor"
  >
    <su-status-bar />
    <!-- 
      :class="[{ 'border-bottom': !props.opacity && props.bg != 'bg-none' }]"
     -->
    <view class="ui-navbar-box">
      <view
        class="ui-bar ss-p-x-20"
        :class="state.isDark ? 'text-white' : 'text-black'"
        :style="[{ height: sys_navBar - sys_statusBar + 'px' }]"
      >
        <view class="icon-box ss-flex" v-if="!is_back && showLeftHome">
          <view class="icon-button icon-button-left ss-flex ss-row-center" @tap="onClickLeft">
            <text class="sicon-back" v-if="hasHistory" />
            <text class="sicon-home" v-else />
          </view>
          <!--          <view class="line"></view>-->
          <!--          <view class="icon-button icon-button-right ss-flex ss-row-center" @tap="onClickRight">-->
          <!--            <text class="sicon-more" />-->
          <!--          </view>-->
        </view>
        <view class="ss-flex" v-if="!!is_back && showLeftHome">
          <image :style="[setImageStyle(20,36)]" style="margin-left: 10rpx;" :src="`${nc_image_path}/nc_back.png`"
                 @tap="onClickLeft"></image>
        </view>
        <slot name="center">
          <view class="center navbar-title flex flex-row align-center">
            <text class="fw_500" :style="{color:color}">{{ title }}</text>
            <view class="background_AI flex flex-row align-center justify-center" v-if="!!isAI">
              AI
            </view>
          </view>
        </slot>
        <view class="addIcon" v-if="showAddIcon">
          <image :src="`${IMG_URL}/genealogy/genealogy_add.png`" style="width: 38rpx;height: 38rpx;"
                 @click.stop="openFeatured"></image>
          <view class="tips_popup flex flex-column align-center" v-if="state.is_featured">
            <view class="list flex align-center justify-between" v-for="(item,index) in state.featured_list"
                  :key="index"
                  @click.stop="goToPath(index)">
              <image :src="`${IMG_URL}${item.image}`"
                     v-if="item.name != '家庭小助手' || mp_code != appVersion2"></image>
              <view class="title" :style="{
                                    borderBottom: index == state.featured_list.length - 1 ? 'none' : '1rpx solid rgba(255,255,255,0.1)'
                                  }"
                    v-if="item.name != '家庭小助手' || mp_code != appVersion2"
              >
                {{ item.name }}
              </view>
            </view>
          </view>
          <view class="all_popup" v-if="state.is_featured" @click.stop="closeFeatured"
                @touchmove.prevent.stop="closeFeatured">
          </view>
        </view>
        <!-- #ifdef MP -->
        <view :style="[state.capsuleStyle]"></view>
        <!-- #endif -->
      </view>
    </view>
  </su-fixed>
</template>

<script setup>
  /**
   * 标题栏 - 基础组件navbar
   *
   * @param {Number}  zIndex = 100  							- 层级
   * @param {Boolean}  back = true 							- 是否返回上一页
   * @param {String}  backtext = ''  							- 返回文本
   * @param {String}  bg = 'bg-white'  						- 公共Class
   * @param {String}  status = ''  							- 状态栏颜色
   * @param {Boolean}  alway = true							- 是否常驻
   * @param {Boolean}  opacity = false  						- 是否开启透明渐变
   * @param {Boolean}  noFixed = false  						- 是否浮动
   * @param {String}  ui = ''									- 公共Class
   * @param {Boolean}  capsule = false  						- 是否开启胶囊返回
   * @param {Boolean}  stopBack = false 					    - 是否禁用返回
   * @param {Boolean}  placeholder = true 					- 是否开启占位
   * @param {Object}   bgStyles = {} 					    	- 背景样式
   *
   */

  import { computed, reactive, onBeforeMount, ref } from 'vue';
  import sheep from '@/sheep';
  import { onPageScroll } from '@dcloudio/uni-app';
  import { showMenuTools, closeMenuTools, showAuthModal, showShareModal } from '@/sheep/hooks/useModal';
  // #ifdef APP-PLUS
  import permision from '@/uni_modules/all-speech/js_sdk/wa-permission/permission';
  // #endif

  // 本地数据
  const state = reactive({
    statusCur: '',
    capsuleStyle: {},
    capsuleBack: {},
    isDark: true,
    is_featured: false,
    featured_list: [
      { name: '添加亲友', image: '/index/addFriendsAndRelatives.png' },
      // #ifndef H5
      { name: '扫一扫', image: '/index/sweep.png', path: '' },
      // #endif
      { name: '今日运势', image: '/index/yourHoroscopeToday.png' },
      { name: '我的二维码', image: '/index/myQRCode.png' },
      { name: '家庭小助手', image: '/index/chat_tips_icon_background.png' },
    ],
  });

  const sys_statusBar = sheep.$platform.device.statusBarHeight;
  const sys_navBar = sheep.$platform.navbar;
  const nc_image_path = computed(() => sheep.$store('AI').nc_image_path);
  const IMG_URL = computed(() => sheep.$store('AI').sq_image_path);
  const isLogin = computed(() => sheep.$store('user').isLogin);

  const setImageStyle = (width, height) => {
    return {
      width: `${width}rpx`,
      height: `${height}rpx`,
    };
  };

  const props = defineProps({
    zIndex: {
      type: Number,
      default: 100,
    },

    title: {
      //返回文本
      type: String,
      default: '',
    },
    bg: {
      type: String,
      default: 'bg-white',
    },
    // 常驻
    alway: {
      type: Boolean,
      default: true,
    },
    opacity: {
      //是否开启滑动渐变
      type: Boolean,
      default: true,
    },
    noFixed: {
      //是否浮动
      type: Boolean,
      default: true,
    },
    ui: {
      type: String,
      default: '',
    },
    capsule: {
      //是否开启胶囊返回
      type: Boolean,
      default: false,
    },
    stopBack: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: [Boolean],
      default: false,
    },
    bgStyles: {
      type: Object,
      default() {
      },
    },
    // 是否是AI
    isAI: {
      type: Boolean,
      default: false,
    },
    // 标题颜色
    color: {
      type: String,
      default: '#FFFFFF',
    },
    // 是否显示金色返回键
    is_back: {
      type: Boolean,
      default: false,
    },
    backgroundColor: {
      type: String,
      default: 'transparent',
    },
    showLeftHome: {
      type: Boolean,
      default: true,
    },
    showAddIcon: {
      type: Boolean,
      default: false,
    },
  });

  const emits = defineEmits(['navback', 'clickLeft']);
  const hasHistory = sheep.$router.hasHistory();

  const mp_code = computed(() => sheep.$store('AI').mp_code);
  const version = computed(() => sheep.$store('AI').version);
  const appVersion = computed(() => sheep.$store('app').info.worship_version);
  const appVersion2 = computed(() => sheep.$store('app').info.worship_version_2);

  onBeforeMount(() => {
    init();
  });

  onPageScroll((e) => {
    let top = e.scrollTop;
    state.isDark = top < sheep.$platform.navbar;
  });

  function onClickLeft() {
    if (hasHistory) {
      sheep.$router.back();
    } else {
      sheep.$router.go('/pages/message/genealogy');
    }
    emits('clickLeft');
  }

  function onClickRight() {
    showMenuTools();
  }

  // 初始化
  const init = () => {
    // #ifdef MP-ALIPAY
    my.hideAllFavoriteMenu();
    // #endif
    state.capsuleStyle = {
      width: sheep.$platform.capsule.width + 'px',
      height: sheep.$platform.capsule.height + 'px',
    };

    state.capsuleBack = state.capsuleStyle;
  };

  function openFeatured() {
    state.is_featured = true;
    uni.$emit('showShare', true);
    uni.$once('closeFeatured', () => {
      state.is_featured = false;
    });
  }

  function closeFeatured() {
    uni.$emit('closeFeatured');
    uni.$emit('showShare', false);
  }

  async function goToPath(index) {
    if (!isLogin.value) {
      showAuthModal();
      return;
    }
    switch (state.featured_list[index].name) {
      case '扫一扫':
        // #ifdef APP-PLUS
        if (sheep.$platform.device.platform.toLocaleLowerCase() == 'ios') {
          uni.scanCode({
            success: (res) => {
              // showAuthModal('addFriend');
            },
          });
        } else {
          let res = plus.navigator.checkPermission('android.permission.CAMERA');
          if (res == 'authorized') {
            uni.scanCode({
              success: (res) => {
                console.log('获取到的信息=>', res);
                if (res.scanType == 'QR_CODE') {
                  const result = res.result.split('?')[1];
                  const qrcode = result.split('=')[1];
                  uni.showModal({
                    title: '授权登录',
                    content: '是否授权登录',
                    success: async (modal) => {
                      if (modal.confirm) {
                        const { code, msg } = await sheep.$api.user.userLogin({
                          qr_code: qrcode,
                          username: sheep.$store('user').userInfo.mobile,
                        });
                        if (code == 1) {
                          sheep.$helper.toast('授权成功');
                        } else {
                          sheep.$helper.toast(msg);
                        }
                      }
                    },
                  });
                }
              },
            });
          } else {
            uni.showModal({
              title: '开启相机权限',
              content: '你还没有开启相机权限，无法使用拾亲扫描功能、拍照或录制视频功能',
              success: async (res) => {
                if (res.confirm) {
                  if (sheep.$platform.device.platform.toLocaleLowerCase() == 'ios') {
                    let limitsOfAuthority = await permision.judgeIosPermission('android.permission.CAMERA');
                    if (limitsOfAuthority == 1) {
                      uni.scanCode({
                        success: (res) => {
                          // showAuthModal('addFriend');
                        },
                      });
                    } else if (limitsOfAuthority == 0) {
                      uni.showModal({
                        title: '开启相机权限',
                        content: '你还没有开启相机权限，无法使用拾亲扫描功能、拍照或录制视频功能',
                        success: async (res) => {
                          if (res.confirm) {
                            permision.gotoAppPermissionSetting();
                          }
                        },
                      });
                    } else {
                      uni.showModal({
                        title: '开启相机权限',
                        content: '你还没有开启相机权限，无法使用拾亲扫描功能、拍照或录制视频功能',
                        success: async (res) => {
                          if (res.confirm) {
                            permision.gotoAppPermissionSetting();
                          }
                        },
                      });
                    }
                  } else {
                    let limitsOfAuthority = await permision.requestAndroidPermission('android.permission.CAMERA');
                    if (limitsOfAuthority == 1) {
                      uni.scanCode({
                        success: (res) => {
                          // showAuthModal('addFriend');
                        },
                      });
                    } else if (limitsOfAuthority == 0) {
                      uni.showModal({
                        title: '开启相机权限',
                        content: '你还没有开启相机权限，无法使用拾亲扫描功能、拍照或录制视频功能',
                        success: async (res) => {
                          if (res.confirm) {
                            permision.gotoAppPermissionSetting();
                          }
                        },
                      });
                    } else {
                      uni.showModal({
                        title: '开启相机权限',
                        content: '你还没有开启相机权限，无法使用拾亲扫描功能、拍照或录制视频功能',
                        success: async (res) => {
                          if (res.confirm) {
                            permision.gotoAppPermissionSetting();
                          }
                        },
                      });
                    }
                  }
                }
              },
            });
          }
        }

        // #endif
        // #ifdef MP-WEIXIN
        uni.scanCode({
          success: async (res) => {
            console.log('获取到的信息=>', res);
            // showAuthModal('addFriend');
            if (res.scanType == 'QR_CODE') {
              const result = res.result.split('?')[1];
              const qrcode = result.split('=')[1];
              uni.showModal({
                title: '授权登录',
                content: '是否授权登录',
                success: async (modal) => {
                  if (modal.confirm) {
                    const { code, msg } = await sheep.$api.user.userLogin({
                      qr_code: qrcode,
                      username: sheep.$store('user').userInfo.mobile,
                    });
                    if (code == 1) {
                      sheep.$helper.toast('授权成功');
                    } else {
                      sheep.$helper.toast(msg);
                    }
                  }
                },
              });
            }
          },
        });
        // #endif
        closeFeatured();
        return;
      case '添加亲友':
        sheep.$router.go('/pages/user/addFriends');
        closeFeatured();
        return;
      case '我的二维码':
        // showShareModal();
        // closeFeatured();
        uni.$emit('setQrCode');
        closeFeatured();
        break;
      case '今日运势':
        sheep.$router.go('/pages/familyPage/anniversariesList', {
          is_flag: 2,
          index: 2,
        });
        closeFeatured();
        break;
      case '家庭小助手':
        if (mp_code.value == appVersion.value) {
          return;
        }
        sheep.$router.go('/pages/message/AIMarketplace');
        closeFeatured();
        break;
    }
  }
</script>

<style lang="scss" scoped>
  .icon-box {
    box-shadow: 0px 0px 4rpx rgba(51, 51, 51, 0.08), 0px 4rpx 6rpx 2rpx rgba(102, 102, 102, 0.12);
    border-radius: 30rpx;
    width: 134rpx;
    height: 56rpx;
    margin-left: 8rpx;
    border: 1px solid rgba(#fff, 0.4);

    .line {
      width: 2rpx;
      height: 24rpx;
      background: #e5e5e7;
    }

    .sicon-back {
      font-size: 32rpx;
    }

    .sicon-home {
      font-size: 32rpx;
    }

    .sicon-more {
      font-size: 32rpx;
    }

    .icon-button {
      width: 67rpx;
      height: 56rpx;

      &-left:hover {
        background: rgba(0, 0, 0, 0.16);
        border-radius: 30rpx 0px 0px 30rpx;
      }

      &-right:hover {
        background: rgba(0, 0, 0, 0.16);
        border-radius: 0px 30rpx 30rpx 0px;
      }
    }
  }

  .navbar-title {
    font-size: 36rpx;
  }

  .tools-icon {
    font-size: 40rpx;
  }

  .ui-navbar-box {
    background-color: transparent;
    width: 100%;

    .ui-bar {
      position: relative;
      z-index: 2;
      white-space: nowrap;
      display: flex;
      position: relative;
      align-items: center;
      justify-content: space-between;

      .left {
        @include flex-bar;

        .back {
          @include flex-bar;

          .back-icon {
            @include flex-center;
            width: 56rpx;
            height: 56rpx;
            margin: 0 10rpx;
            font-size: 46rpx !important;

            &.opacityIcon {
              position: relative;
              border-radius: 50%;
              background-color: rgba(127, 127, 127, 0.5);

              &::after {
                content: '';
                display: block;
                position: absolute;
                height: 200%;
                width: 200%;
                left: 0;
                top: 0;
                border-radius: inherit;
                transform: scale(0.5);
                transform-origin: 0 0;
                opacity: 0.1;
                border: 1px solid currentColor;
                pointer-events: none;
              }

              &::before {
                transform: scale(0.9);
              }
            }
          }

          /* #ifdef  MP-ALIPAY */
          ._icon-back {
            opacity: 0;
          }

          /* #endif */
        }

        .capsule {
          @include flex-bar;
          border-radius: 100px;
          position: relative;

          &.dark {
            background-color: rgba(255, 255, 255, 0.5);
          }

          &.light {
            background-color: rgba(0, 0, 0, 0.15);
          }

          &::after {
            content: '';
            display: block;
            position: absolute;
            height: 60%;
            width: 1px;
            left: 50%;
            top: 20%;
            background-color: currentColor;
            opacity: 0.1;
            pointer-events: none;
          }

          &::before {
            content: '';
            display: block;
            position: absolute;
            height: 200%;
            width: 200%;
            left: 0;
            top: 0;
            border-radius: inherit;
            transform: scale(0.5);
            transform-origin: 0 0;
            opacity: 0.1;
            border: 1px solid currentColor;
            pointer-events: none;
          }

          .capsule-back,
          .capsule-home {
            @include flex-center;
            flex: 1;
          }

          &.isFristPage {
            .capsule-back,
            &::after {
              display: none;
            }
          }
        }
      }

      .right {
        @include flex-bar;

        .right-content {
          @include flex;
          flex-direction: row-reverse;
        }
      }

      .center {
        @include flex-center;
        text-overflow: ellipsis;
        // text-align: center;
        position: absolute;
        left: 50%;
        transform: translateX(-50%);

        .image {
          display: block;
          height: 36px;
          max-width: calc(100vw - 200px);
        }
      }
    }

    .ui-bar-bg {
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      z-index: 1;
      pointer-events: none;
    }
  }

  .background_AI {
    width: 66rpx;
    height: 30rpx;
    background: url($uni-bg-url + '/chat_icon_ai.png') no-repeat;
    background-size: 66rpx 30rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 16rpx;
    color: #FFFFFF;
    margin-left: 15rpx;
  }


  .addIcon {
    position: absolute;
    /* #ifdef MP */
    left: 44rpx;
    /* #endif */
    /* #ifndef MP */
    right: 44rpx;
    /* #endif */
    top: 50%;
    transform: translateY(-50%);
    width: 38rpx;
    height: 38rpx;

    .tips_popup {
      width: 240rpx;
      //height: 390rpx;
      position: absolute;
      /* #ifdef MP */
      bottom: -495rpx;
      left: -20rpx;
      /* #endif */
      /* #ifdef APP-PLUS */
      bottom: -505rpx;
      right: -20rpx;
      /* #endif */
      /* #ifdef H5 */
      bottom: -410rpx;
      right: -20rpx;
      /* #endif */
      background: #4e4747;
      border-radius: 8rpx;
      z-index: 999999;

      &::before {
        content: '';
        position: absolute;
        width: 0;
        height: 0;
        border-left: 11rpx solid transparent;
        border-right: 11rpx solid transparent;
        border-bottom: 11rpx solid #4e4747;
        top: -11rpx;
        /* #ifdef MP */
        left: 15.5%;
        /* #endif */
        /* #ifndef MP */
        right: 7%;
        /* #endif */
        transform: translateX(-50%);
      }

      .list {
        width: 200rpx;

        image {
          width: 30rpx;
          height: 30rpx;
        }

        .title {
          width: 150rpx;
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          font-size: 30rpx;
          color: #FFFFFF;
          padding: 27rpx 0;
        }
      }
    }

    .all_popup {
      position: fixed;
      width: 100vh;
      height: 100vh;
      top: 0;
      /* #ifdef MP */
      left: -44rpx;
      /* #endif */
      /* #ifndef MP */
      right: -44rpx;
      /* #endif */
      background: transparent;
    }
  }
</style>
